package com.atguigu.gmall.index.aspect;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.index.annotation.GmallCache;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.ClientEndpoint;
import java.lang.reflect.Method;
import java.net.SocketTimeoutException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Aspect
public class GmallCacheAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RBloomFilter bloomFilter;

    @Around("@annotation(com.atguigu.gmall.index.annotation.GmallCache)")
    public Object cacheAdvice(ProceedingJoinPoint joinPoint) throws Throwable {

        // 获取方法签名
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        // 获取方法对象
        Method method = signature.getMethod();
        // 获取方法上的注解对象
        GmallCache gmallCache = method.getAnnotation(GmallCache.class);

        // 缓存前缀
        String prefix = gmallCache.prefix();
        // 方法参数
        String args = StringUtils.join(joinPoint.getArgs(), ",");
        // 缓存的key
        String key = prefix + args;
        // 1.先查询缓存，如果缓存命中直接返回
        String json = this.redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(json)) {
            return JSON.parseObject(json, method.getReturnType());
        }

        // 为了防止缓存穿透，添加布隆过滤器
        if (!bloomFilter.contains(key)){
            return null;
        }

        // 2.为了防止缓存击穿添加分布式锁
        RLock fairLock = this.redissonClient.getFairLock(gmallCache.lock() + args);
        fairLock.lock();

        try {
            // 3.再次查询缓存，如果命中则直接返回
            String json2 = this.redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(json2)) {
                return JSON.parseObject(json2, method.getReturnType());
            }

            // 4.执行目标方法
            Object result = joinPoint.proceed(joinPoint.getArgs());

            // 5.把目标方法的返回结果集放入缓存，并释放分布式锁
            if (result != null) {
                int timeout = gmallCache.timeout() + new Random().nextInt(gmallCache.random());
                this.redisTemplate.opsForValue().set(key, JSON.toJSONString(result), timeout, TimeUnit.MINUTES);
            }

            return result;
        } finally {
            fairLock.unlock();
        }
    }

    @Pointcut("execution(* com.atguigu.gmall.index.service.*.*(..))")
    public void pointcut(){
    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        System.out.println("前置通知" + joinPoint.getTarget().getClass().getName() + "." + method.getName());
    }

    @AfterReturning(value = "pointcut()", returning = "result")
    public void afterReturning(Object result){
        System.out.println("返回后通知：" + result);
    }

    @AfterThrowing(value = "pointcut()", throwing = "ex")
    public void afterThrowing(Exception ex){
        System.out.println("异常后通知：" + ex.getMessage());
    }

    @After(value = "pointcut()")
    public void after(){
        System.out.println("最终通知");
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        System.out.println("环绕前增强。。。。");
        Object result = joinPoint.proceed(joinPoint.getArgs());
        System.out.println("环绕后增强。。。。");

        return result;
    }
}
